package org.cn.lennon.mybatis.factory;

import org.cn.lennon.mybatis.config.Configuration;
import org.cn.lennon.mybatis.executors.ExecutorType;
import org.cn.lennon.mybatis.executors.Executors;
import org.cn.lennon.mybatis.executors.impl.CacheExecutors;
import org.cn.lennon.mybatis.executors.impl.SimpleExecutors;
import org.cn.lennon.mybatis.session.SqlSession;
import org.cn.lennon.mybatis.session.impl.DefaultSqlSession;
import org.cn.lennon.mybatis.transcation.Transaction;
import org.cn.lennon.mybatis.transcation.impl.JdbcTransaction;
import org.cn.lennon.mybatis.transcation.impl.connection.ConnestionPool;

/**
 * sql Session factory
 * 
 * @author Administrator
 *
 */
public class SqlSessionFactory {
	
	private String classPath;
	private final Configuration configuration;

	public SqlSessionFactory(Configuration configuration) {
		this.configuration = configuration;
	}
	
	public String getClassPath() {
		return classPath;
	}

	public void setClassPath(String classPath) {
		this.classPath = classPath;
	}

	public Configuration getConfiguration() {
		return configuration;
	}

	public SqlSession openSession(ExecutorType executorType) {
		Transaction transaction = new JdbcTransaction(ConnestionPool.getConnection(), true);
		return new DefaultSqlSession(configuration, newExecutor(executorType, transaction));
	}
	
	public SqlSession openSession(ExecutorType executorType, boolean autoCommit) {
		Transaction transaction = new JdbcTransaction(ConnestionPool.getConnection(), autoCommit);
		return new DefaultSqlSession(configuration, newExecutor(executorType, transaction));
	}
	
	public SqlSession openSession(boolean autoCommit) {
		Transaction transaction = new JdbcTransaction(ConnestionPool.getConnection(), autoCommit);
		return new DefaultSqlSession(configuration, newExecutor(ExecutorType.SIMPLE, transaction));
	}
	
	public SqlSession openSession() {
		Transaction transaction = new JdbcTransaction(ConnestionPool.getConnection(), true);
		return new DefaultSqlSession(configuration, newExecutor(ExecutorType.SIMPLE, transaction));
	}
	
	public void builde() {
		configuration.builde(classPath);
	}
	
	private Executors newExecutor(ExecutorType executorType, Transaction transaction) {
		if(ExecutorType.SIMPLE.equals(executorType)) {
			return new SimpleExecutors(transaction);
		}else if(ExecutorType.CACHE.equals(executorType)) {
			return new CacheExecutors(new SimpleExecutors(transaction));
		}
		return new SimpleExecutors(transaction);
	}
}
